package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.dao.CompanyEmployeeDao;
import com.xuanzheng.company.dao.impl.CompanyEmployeeDaoImpl;
import com.xuanzheng.company.entity.CompanyEmployee;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;
import com.xuanzheng.company.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/userAccount")
public class UserAccountServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    private CompanyEmployeeDao companyEmployeeDao = new CompanyEmployeeDaoImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(gson.toJson(result));
            return;
        }

        User currentUser = (User) session.getAttribute("user");
        String action = request.getParameter("action");

        if (action == null) {
            result.put("success", false);
            result.put("message", "未指定操作类型");
            out.print(gson.toJson(result));
            return;
        }

        switch (action) {
            case "leave_company":
                handleLeaveCompany(currentUser, result, session);
                break;
            case "delete_account":
                handleDeleteAccount(currentUser, result, session);
                break;
            default:
                result.put("success", false);
                result.put("message", "不支持的操作类型");
                break;
        }

        out.print(gson.toJson(result));
    }

    private void handleLeaveCompany(User user, Map<String, Object> result, HttpSession session) {
        // 检查用户是否在公司中
        if (user.getCompanyId() == null || user.getCompanyId().isEmpty()) {
            result.put("success", false);
            result.put("message", "您当前未加入任何公司");
            return;
        }

        // 获取用户的公司员工记录
        CompanyEmployee employee = companyEmployeeService.getByUserId(user.getId());
        if (employee == null) {
            result.put("success", false);
            result.put("message", "找不到您的公司员工记录");
            return;
        }

        // 检查是否是公司负责人，不允许负责人自己退出公司
        if ("负责人".equals(employee.getPosition())) {
            result.put("success", false);
            result.put("message", "公司负责人不能退出公司");
            return;
        }
        
        // 检查用户是否已经提交了离职申请
        CompanyEmployee resignation = companyEmployeeService.getUserResignation(user.getId());
        
        // 如果没有离职申请或离职申请未被批准，则不允许直接退出公司
        if (resignation == null) {
            result.put("success", false);
            result.put("message", "请先提交离职申请，等待公司批准后才能退出公司");
            result.put("needResignation", true);
            return;
        }
        
        // 如果离职申请状态不是已批准(4)，也不允许退出
        if (resignation.getStatus() != 4) {
            result.put("success", false);
            if (resignation.getStatus() == 3) {
                result.put("message", "您的离职申请正在审核中，请等待公司批准后再退出公司");
            } else {
                result.put("message", "您的离职申请未被批准，无法退出公司");
            }
            return;
        }

        // 离职申请已批准，可以执行退出公司操作
        boolean success = companyEmployeeDao.fireEmployee(employee.getId());
        
        if (success) {
            // 更新会话中的用户对象
            user.setCompanyId(null);
            user.setEmployeeNumber(null);
            session.setAttribute("user", user);
            
            result.put("success", true);
            result.put("message", "您已成功退出公司");
        } else {
            result.put("success", false);
            result.put("message", "退出公司失败，请稍后重试");
        }
    }

    private void handleDeleteAccount(User user, Map<String, Object> result, HttpSession session) {
        System.out.println("开始处理注销账号请求 - 用户ID: " + user.getId() + ", 姓名: " + user.getName());
        
        // 检查用户是否已经退出公司
        if (user.getCompanyId() != null && !user.getCompanyId().isEmpty()) {
            System.out.println("注销失败 - 用户尚未退出公司, 公司ID: " + user.getCompanyId());
            result.put("success", false);
            result.put("message", "请先退出公司，再注销账号");
            return;
        }

        try {
            System.out.println("开始执行删除用户操作...");
            // 执行注销账号操作（彻底删除用户数据）
            boolean success = userService.deleteUserById(user.getId());
            
            if (success) {
                System.out.println("用户删除成功 - 用户ID: " + user.getId());
                // 注销成功，销毁会话
                session.invalidate();
                
                result.put("success", true);
                result.put("message", "账号已成功注销，您的账号信息已被删除");
                result.put("redirect", "index.html"); // 重定向到登录页
            } else {
                System.out.println("用户删除失败 - 用户ID: " + user.getId() + ", 数据库操作返回false");
                result.put("success", false);
                result.put("message", "注销账号失败，请稍后重试");
            }
        } catch (Exception e) {
            System.err.println("注销账号过程发生异常: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "注销账号失败: " + e.getMessage());
        }
    }
} 